package com.qiqidream.admin.common.response;

import com.alibaba.fastjson.JSONObject;
import com.qiqidream.admin.common.config.EncodeConfig;
import com.qiqidream.admin.common.utils.EncodeUtil;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.annotation.Resource;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;

/**
 * 统一响应体处理器
 * @author QiQiDream
 * @since 2019/12/7 16:29
 */
@ControllerAdvice(annotations = BaseResponse.class)
public class ResponseResultHandlerAdvice implements ResponseBodyAdvice<Object> {

    @Resource
    EncodeConfig encodeConfig;

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {

        if(MediaType.APPLICATION_JSON.equals(selectedContentType) || MediaType.APPLICATION_JSON_UTF8.equals(selectedContentType)){ // 判断响应的Content-Type为JSON格式的body

            if(body instanceof ResponseResult){
                // 如果响应返回的对象为统一响应体，则直接返回body
                return body;
            }else{
                // 只有正常返回的结果才会进入这个判断流程，所以返回正常成功的状态码
                try {
                    //api加密返回
                    if (encodeConfig.getEnabled()) {
                        String encrypt = EncodeUtil.encrypt(body);
                        return ResponseResult.success(ResponseCode.ENCRYPT_SUCCESS, encrypt);
                    }
                    //api正常返回
                    return ResponseResult.success(ResponseCode.SUCCESS, body);
                } catch (Exception e){
                    return ResponseResult.failed("加密失败");
                }
            }
        }
        // 非JSON格式body直接返回即可
        return body;
    }

    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return true;
    }

}
